//
//  DemoViewController.m
//  MySpaceID
//
//  Created by haider on Monday6/8/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "MySpaceID_DemoViewController.h"
#import "OffsiteContext.h"
#import "XPathQuery.h" 

@implementation MySpaceID_DemoViewController
@synthesize context;
@synthesize api;
@synthesize urlReturn;
@synthesize userId;
@synthesize masterFriendList;
@synthesize masterImageUrl;
@synthesize masterUserIds;
@synthesize masterUsername;
@synthesize friendImageView;
@synthesize profileImageView;
@synthesize slider;
@synthesize statusTextView;
@synthesize statusTextField;


- (void)pickerView:(UIPickerView *)aPickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	/*
	printf("User selected row %d for component %d\n", row, component);
	
	int first = [pickerView selectedRowInComponent:0];
	int second = [pickerView selectedRowInComponent:1];
	int delta = first;
	NSString *userId1 = 0;
	NSString *userId2 = 0;
	NSString *userImageUri1 = @"";
	NSString *userImageUri2 = @"";
	
	NSDictionary *node = [masterUserIds objectAtIndex:delta];
	for (id key in node) {
		NSLog(@"key: %@, value: %@", key, [node objectForKey:key]);
	}
	NSString *value = [node objectForKey:@"nodeContent"];
	if(value)
	{
		userId1 = value;
	}
	node = [masterImageUrl objectAtIndex:delta];
	value = [node objectForKey:@"nodeContent"];
	if(value)
		userImageUri1 = value;
	
	
	
	delta = second + 10;
	node = [masterUserIds objectAtIndex:delta];
	for (id key in node) {
		NSLog(@"key: %@, value: %@", key, [node objectForKey:key]);
	}
	value = [node objectForKey:@"nodeContent"];
	if(value)
	{
		userId2 = value;
	}
	node = [masterImageUrl objectAtIndex:delta];
	value = [node objectForKey:@"nodeContent"];
	if(value)
		userImageUri2 = value;
	
	NSURL *url = [NSURL URLWithString: userImageUri1];
	UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
//	UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20.0f, 120.0f, 80.0f, 80.0f)]; 
	UIImageView *iV = (UIImageView*)[self.view viewWithTag:1000];
	[iV setImage:img];
	url = [NSURL URLWithString: userImageUri2];
	img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
	iV = (UIImageView*)[self.view viewWithTag:1001];
	[iV setImage:img];
	 
	 */
}



-(void) logIn

{
	[context getRequestToken];
	
}

-(void) logOut
{
	[context logOut];
	
	for(UIView *view in self.view.subviews)
	{
		[view removeFromSuperview];
		
	}
	// Add a left buttonˆ
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
											  initWithTitle:@"Login" 
											  style:UIBarButtonItemStylePlain 
											  target:self 
											  action:@selector(logIn)] autorelease];
	
}


- (void) parseFriendsData: (NSData*) data
{
	
	if(data)
	{
		
		masterFriendList = PerformXMLXPathQuery2(data, @"//ms:user/ms:friends/ms:user", @"ms", @"api-v1.myspace.com");
		NSLog([NSString stringWithFormat: @"%d", [masterFriendList count]]);
		masterUserIds = PerformXMLXPathQuery2(data, @"//ms:user/ms:friends/ms:user/ms:userid", @"ms", @"api-v1.myspace.com");
		NSLog([NSString stringWithFormat: @"%d", [masterFriendList count]]);
		masterImageUrl = PerformXMLXPathQuery2(data, @"//ms:user/ms:friends/ms:user/ms:imageuri", @"ms", @"api-v1.myspace.com");
		NSLog([NSString stringWithFormat: @"%d", [masterFriendList count]]);
		masterUsername = PerformXMLXPathQuery2(data, @"//ms:user/ms:friends/ms:user/ms:displayname", @"ms", @"api-v1.myspace.com");
		NSLog([NSString stringWithFormat: @"%d", [masterFriendList count]]);
		[masterUserIds retain];
		[masterUsername retain];
		[masterImageUrl retain];
		
		/*
		// Add the picker
		float height = 216.0f;
		pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0.0f, 416.0f - height, 320.0f, height)];
		pickerView.delegate = self;
		pickerView.showsSelectionIndicator = YES;
		// [pickerView setSoundsEnabled:NO];
		[self.view addSubview:pickerView];
		[pickerView release];
		
		// Add a results label
		comboView = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 170.0f, 320.0f, 32.0f)];
		[comboView setBackgroundColor:[UIColor clearColor]];
		[comboView setTextAlignment:UITextAlignmentCenter];
		//[comboView setText:@"Left-00  Right-00  Left-00"];
		[self.view addSubview:comboView];
		[comboView release];
		*/
//		NSURL *url = [NSURL URLWithString: @"http://c3.ac-images.myspacecdn.com/images01/94/s_9f113c9600685e5e76e9ab07ed41ad4e.jpg"];
//		UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
		UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(20.0f, 120.0f, 80.0f, 80.0f)]; 
		[imgView setTag:1000];
		[imgView setUserInteractionEnabled:NO];
		//[imgView setImage:img];
		[[self view] addSubview:imgView];
		[imgView release];
		
		imgView = [[UIImageView alloc] initWithFrame:CGRectMake(180.0f, 120.0f, 80.0f, 80.0f)]; 
		[imgView setTag:1001];
		[imgView setUserInteractionEnabled:NO];
		//[imgView setImage:img];
		[[self view] addSubview:imgView];
		[imgView release];
	}
	
	
	
}
// This method catches the return action
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	return YES;
}
- (void) updateButtonClicked: (UIButton *) button
{
	UITextField *textField = (UITextField*)[self.view viewWithTag:1002];
	
	if(context && api)
	{
		[api setMoodStatus:userId moodId:0 moodName:nil moodPictureName:nil status:[textField text]];
	}
	//[textField release];
}
- (void) parseMoodData: (NSData*) data
{
	if(data)
	{
		NSArray *result = PerformXMLXPathQuery2(data	, @"//ms:user/ms:mood", @"ms", @"api-v1.myspace.com");
		NSDictionary *node = [result objectAtIndex:0];
		NSString *value = [node objectForKey:@"nodeContent"];
		if(value)
		{
			self.title = value;
		}
		UITextField *textField = [[[UITextField alloc] initWithFrame:CGRectMake(100.0f, 0.0f, 200.0f, 30.0f)] retain];
		[textField setBorderStyle:UITextBorderStyleRoundedRect];
		[textField setTag: 1002];
		textField.placeholder = @"update status here";
		textField.autocorrectionType = UITextAutocorrectionTypeNo;
		textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
		textField.returnKeyType = UIReturnKeyDone;
		textField.clearButtonMode = UITextFieldViewModeWhileEditing;
//		textField.delegate = self;
		[[self view] addSubview:textField];
		[textField release];
		
		
		UIButton *updateButton = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain] ;
		[updateButton setFrame:CGRectMake(150.0f, 30.0f, 80.0f, 30.0f)];
		[updateButton setTitle:@"Update" forState:UIControlStateNormal];
		[updateButton addTarget:self action:@selector(updateButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
		[[self view] addSubview:updateButton];
		//[updateButton release];
		
	}
}

- (void) parseUserData: (NSData*) data
{
	if(data)
	{
		NSArray *result = PerformXMLXPathQuery2(data, @"//ms:user/ms:imageuri", @"ms", @"api-v1.myspace.com");
		NSDictionary *node = [result objectAtIndex:0];
		NSString *value = [node objectForKey:@"nodeContent"];
		if(value)
		{
			NSURL *url = [NSURL URLWithString: value];
			UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
			UIImageView *imgView = [[UIImageView alloc] initWithImage:img];
			[imgView setUserInteractionEnabled:NO];
			[[self view] addSubview:imgView];
			[imgView release];
		}
		result = PerformXMLXPathQuery2(data, @"//ms:user/ms:userid", @"ms", @"api-v1.myspace.com");
		node = [result objectAtIndex:0];
		value = [node objectForKey:@"nodeContent"];
		if(value)
		{
			userId = [value integerValue];
		}
	}
}


 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
	 [super viewDidLoad];
	 UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	 self.view = contentView;
	 contentView.backgroundColor = [UIColor whiteColor];
	 [contentView release];
	 
	 OffsiteContext *myContext = nil;
	 if(myContext == nil)
	 {
		 myContext = [OffsiteContext contextWithConsumerKey:@"18bed0f4247a4f79bc9941bfed5b534c"  
											 consumerSecret:@"2e8ebdafbef844a5929086e659e4188c" tokenKey:nil tokenSecret:nil] ;
		 [myContext setUrlScheme:@"myspaceid2"];
		 
		 
	 }
	 NSString *returnUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"url"];
	 if(returnUrl)
	 {
		 [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"url"];
		 [[NSUserDefaults standardUserDefaults] synchronize];
		 [myContext getAccessToken];		
	 }
	 
	 bool loggedIn = [myContext isLoggedIn];
	 if(loggedIn)
	 {
		 // Add a left button
		 self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
												   initWithTitle:@"Logout" 
												   style:UIBarButtonItemStylePlain 
												   target:self 
												   action:@selector(logOut)] autorelease];
		 
		 self.api = [RestV1 apiWithContext: myContext] ;
		 NSData *userData = [api getCurrentUser];
		 [self parseUserData:userData];
		 userData = [api getMood:userId];
		 [self parseMoodData:userData];
		 userData = [api getFriends:userId];
		 [self parseFriendsData:userData];
		 /*
		  NSInteger *page = (NSInteger*)1;
		  NSInteger *pageSize = (NSInteger*)10;
		  userData = [api getMoodsList:userId];
		  userData = [api getAlbums:userId];
		  userData = [api getAlbums:userId page:page pageSize:pageSize];
		  userData = [api getAlbum:userId albumId:(NSInteger*)2000];
		  userData = [api getFriends:userId page:(NSInteger*)2 pageSize:(NSInteger*)15];
		  userData = [api getFriendStatus:userId];
		  userData = [api getPhotos:userId]; 
		  userData = [api getPhotos:userId page:page pageSize:pageSize];
		  userData = [api getFullProfile:userId];
		  userData = [api getFriendship:userId friendIds:[NSArray arrayWithObjects:@"1234", @"65815518", nil]];
		  userData = [api getStatus:userId];
		  userData = [api getVideos:userId]; 
		  userData = [api getActivities:userId];
		  userData = [api getFriendActivities:userId];
		  
		  
		  userData = [api getFriendAppData:userId];
		  userData = [api getIndicators:userId];
		  
		  userData = [api getGlobalAppData];
		  NSDictionary *appData = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:@"keyvalue1", @"keyvalue2", nil] forKeys:[NSArray arrayWithObjects:@"key1", @"key2", nil]];
		  [api addGlobalAppData:appData];
		  userData = [api getGlobalAppData];
		  [api deleteGlobalAppData:[NSArray arrayWithObjects:@"key1", @"key2", nil]];
		  userData = [api getGlobalAppData];
		  
		  userData = [api getUserAppData:userId];
		  NSDictionary *userAppData = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:@"keyuservalue1", @"keyuservalue2", nil] forKeys:[NSArray arrayWithObjects:@"userkey1", @"userkey2", nil]];
		  [api addUserAppData:userId userAppDataPairs:userAppData];
		  userData = [api getUserAppData:userId];
		  [api deleteUserAppData:userId keys:[NSArray arrayWithObjects:@"userkey1", @"userkey2", nil]];
		  userData =  [api getUserAppData:userId];
		  
		  
		  */
	 }
	 else
	 {
		 // Add a left button
		 self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc]
												   initWithTitle:@"Login" 
												   style:UIBarButtonItemStylePlain 
												   target:self 
												   action:@selector(logIn)] autorelease];
	 }
	 
 }
 

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[context release];
	[api release];
	[masterFriendList release];
	[masterImageUrl release];
	[masterUserIds release];
	[masterUsername release];
	[friendImageView release];
	[profileImageView release];
	[super dealloc];
}


@end
